import React, { useState } from 'react';
import { Card, Table, Button, Space, Tag, Modal, Form, Input, Select, Switch, Tabs, Transfer, Tree } from 'antd';
import { PlusOutlined, UserOutlined, TeamOutlined, SettingOutlined, LockOutlined } from '@ant-design/icons';
import type { TransferItem } from 'antd/es/transfer';
import type { ColumnType } from 'antd/es/table';
import type { Key } from 'react';

const { Option } = Select;

interface Role {
  id: string;
  name: string;
  description: string;
  permissions: string[];
}

interface User {
  id: string;
  name: string;
  email: string;
  department: string;
  roles: string[];
  lastLogin: string;
  status: 'active' | 'inactive';
}

interface Resource {
  id: string;
  name: string;
  description: string;
  type: string;
}

// 使用简单对象模拟存储
const permissionStore = {
  roles: [
    { id: 'admin', name: '管理员', description: '系统管理员，拥有所有权限', permissions: ['doc_read', 'doc_write', 'doc_delete', 'user_manage', 'role_manage', 'system_config'] },
    { id: 'editor', name: '编辑者', description: '可以创建和编辑文档', permissions: ['doc_read', 'doc_write'] },
    { id: 'viewer', name: '查看者', description: '只能查看文档', permissions: ['doc_read'] },
  ] as Role[],
  
  users: Array.from({ length: 10 }).map((_, i) => ({
    id: `user-${i}`,
    name: `用户${i}`,
    email: `user${i}@example.com`,
    department: ['技术部', '市场部', '人力资源', '财务部'][Math.floor(Math.random() * 4)],
    roles: i === 0 ? ['admin'] : i < 3 ? ['editor'] : ['viewer'],
    lastLogin: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
    status: Math.random() > 0.2 ? 'active' : 'inactive',
  })) as User[],
  
  resources: [
    { id: 'doc_read', name: '文档查看', description: '查看文档的权限', type: '文档' },
    { id: 'doc_write', name: '文档编辑', description: '创建和编辑文档的权限', type: '文档' },
    { id: 'doc_delete', name: '文档删除', description: '删除文档的权限', type: '文档' },
    { id: 'user_manage', name: '用户管理', description: '管理用户的权限', type: '用户' },
    { id: 'role_manage', name: '角色管理', description: '管理角色的权限', type: '系统' },
    { id: 'system_config', name: '系统配置', description: '配置系统的权限', type: '系统' },
  ] as Resource[],
  
  addRole: (role: Omit<Role, 'id'>) => {
    const newRole = { ...role, id: `role-${Date.now()}` };
    permissionStore.roles.push(newRole as Role);
    return newRole;
  },
  
  updateRole: (id: string, role: Partial<Role>) => {
    const index = permissionStore.roles.findIndex(r => r.id === id);
    if (index !== -1) {
      permissionStore.roles[index] = { ...permissionStore.roles[index], ...role };
    }
  },
  
  addUser: (user: Omit<User, 'id'>) => {
    const newUser = { ...user, id: `user-${Date.now()}` };
    permissionStore.users.push(newUser as User);
    return newUser;
  },
  
  updateUser: (id: string, user: Partial<User>) => {
    const index = permissionStore.users.findIndex(u => u.id === id);
    if (index !== -1) {
      permissionStore.users[index] = { ...permissionStore.users[index], ...user };
    }
  },
};

const usePermissionStore = () => permissionStore;

const PermissionManager: React.FC = () => {
  const permissions = usePermissionStore();
  const { roles, users, resources } = permissions;
  
  const [activeTab, setActiveTab] = useState('users');
  const [userModalVisible, setUserModalVisible] = useState(false);
  const [roleModalVisible, setRoleModalVisible] = useState(false);
  const [editMode, setEditMode] = useState(false);
  const [currentUser, setCurrentUser] = useState<User | null>(null);
  const [currentRole, setCurrentRole] = useState<Role | null>(null);
  
  const [userForm] = Form.useForm();
  const [roleForm] = Form.useForm();
  
  // 处理添加/编辑用户
  const handleAddEditUser = () => {
    setEditMode(false);
    setCurrentUser(null);
    userForm.resetFields();
    setUserModalVisible(true);
  };
  
  // 处理编辑用户
  const handleEditUser = (user: User) => {
    setEditMode(true);
    setCurrentUser(user);
    userForm.setFieldsValue(user);
    setUserModalVisible(true);
  };
  
  // 处理添加/编辑角色
  const handleAddEditRole = () => {
    setEditMode(false);
    setCurrentRole(null);
    roleForm.resetFields();
    setRoleModalVisible(true);
  };
  
  // 处理编辑角色
  const handleEditRole = (role: Role) => {
    setEditMode(true);
    setCurrentRole(role);
    roleForm.setFieldsValue(role);
    setRoleModalVisible(true);
  };
  
  // 保存用户
  const handleSaveUser = () => {
    userForm.validateFields().then(values => {
      if (editMode && currentUser) {
        permissions.updateUser(currentUser.id, values);
      } else {
        permissions.addUser(values);
      }
      setUserModalVisible(false);
    });
  };
  
  // 保存角色
  const handleSaveRole = () => {
    roleForm.validateFields().then(values => {
      if (editMode && currentRole) {
        permissions.updateRole(currentRole.id, values);
      } else {
        permissions.addRole(values);
      }
      setRoleModalVisible(false);
    });
  };
  
  // 用户表格列
  const userColumns: ColumnType<User>[] = [
    {
      title: '用户名',
      dataIndex: 'name',
      key: 'name',
      render: (text: string) => (
        <Space>
          <UserOutlined />
          {text}
        </Space>
      ),
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department',
      filters: [
        { text: '技术部', value: '技术部' },
        { text: '市场部', value: '市场部' },
        { text: '人力资源', value: '人力资源' },
        { text: '财务部', value: '财务部' },
      ],
      onFilter: (value: boolean | Key, record: User) => 
        typeof value === 'boolean' ? false : record.department === value,
    },
    {
      title: '角色',
      dataIndex: 'roles',
      key: 'roles',
      render: (roles: string[]) => (
        <>
          {roles.map(roleId => {
            const role = permissions.roles.find(r => r.id === roleId);
            return role ? (
              <Tag color="blue" key={roleId}>
                {role.name}
              </Tag>
            ) : null;
          })}
        </>
      ),
    },
    {
      title: '最后登录',
      dataIndex: 'lastLogin',
      key: 'lastLogin',
      render: (date: string) => new Date(date).toLocaleString(),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? '活跃' : '非活跃'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: unknown, record: User) => (
        <Space>
          <Button 
            type="link" 
            size="small"
            onClick={() => handleEditUser(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            danger 
            size="small"
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];
  
  // 角色表格列
  const roleColumns = [
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string) => (
        <Space>
          <TeamOutlined />
          {text}
        </Space>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '权限',
      dataIndex: 'permissions',
      key: 'permissions',
      render: (permissions: string[]) => (
        <Space wrap>
          {permissions.map(permId => {
            const perm = resources.find(r => r.id === permId);
            return perm ? (
              <Tag key={permId}>{perm.name}</Tag>
            ) : null;
          })}
        </Space>
      ),
    },
    {
      title: '用户数',
      key: 'userCount',
      render: (_: unknown, record: Role) => {
        const count = users.filter(u => u.roles.includes(record.id)).length;
        return count;
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_: unknown, record: Role) => (
        <Space>
          <Button
            type="link"
            size="small"
            onClick={() => handleEditRole(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            size="small"
            disabled={record.id === 'admin'}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];
  
  return (
    <Card title="权限管理">
      <Tabs
        activeKey={activeTab}
        onChange={setActiveTab}
        items={[
          {
            key: 'users',
            label: (
              <span>
                <UserOutlined />
                用户管理
              </span>
            ),
            children: (
              <>
                <div style={{ marginBottom: 16, textAlign: 'right' }}>
                  <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={handleAddEditUser}
                  >
                    添加用户
                  </Button>
                </div>
                <Table
                  dataSource={users}
                  columns={userColumns}
                  rowKey="id"
                />
              </>
            )
          },
          {
            key: 'roles',
            label: (
              <span>
                <TeamOutlined />
                角色管理
              </span>
            ),
            children: (
              <>
                <div style={{ marginBottom: 16, textAlign: 'right' }}>
                  <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={handleAddEditRole}
                  >
                    添加角色
                  </Button>
                </div>
                <Table
                  dataSource={roles}
                  columns={roleColumns}
                  rowKey="id"
                />
              </>
            )
          },
          {
            key: 'resources',
            label: (
              <span>
                <LockOutlined />
                资源权限
              </span>
            ),
            children: (
              <Table
                dataSource={resources}
                columns={[
                  {
                    title: '权限名称',
                    dataIndex: 'name',
                    key: 'name',
                  },
                  {
                    title: '描述',
                    dataIndex: 'description',
                    key: 'description',
                  },
                  {
                    title: '类型',
                    dataIndex: 'type',
                    key: 'type',
                    render: (type: string) => <Tag>{type}</Tag>,
                  },
                ]}
                rowKey="id"
              />
            )
          }
        ]}
      />
      
      {/* 用户表单模态框 */}
      <Modal
        title={`${editMode ? '编辑' : '添加'}用户`}
        open={userModalVisible}
        onOk={handleSaveUser}
        onCancel={() => setUserModalVisible(false)}
      >
        <Form
          form={userForm}
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input prefix={<UserOutlined />} placeholder="请输入用户名" />
          </Form.Item>
          
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          
          <Form.Item
            name="department"
            label="部门"
          >
            <Select placeholder="请选择部门">
              <Option value="技术部">技术部</Option>
              <Option value="市场部">市场部</Option>
              <Option value="人力资源">人力资源</Option>
              <Option value="财务部">财务部</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="roles"
            label="角色"
          >
            <Select mode="multiple" placeholder="请选择角色">
              {roles.map(role => (
                <Option key={role.id} value={role.id}>
                  {role.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item
            name="status"
            label="状态"
            valuePropName="checked"
          >
            <Switch 
              checkedChildren="活跃" 
              unCheckedChildren="非活跃" 
              defaultChecked 
            />
          </Form.Item>
        </Form>
      </Modal>
      
      {/* 角色表单模态框 */}
      <Modal
        title={`${editMode ? '编辑' : '添加'}角色`}
        open={roleModalVisible}
        onOk={handleSaveRole}
        onCancel={() => setRoleModalVisible(false)}
        width={700}
      >
        <Form
          form={roleForm}
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="角色名称"
            rules={[{ required: true, message: '请输入角色名称' }]}
          >
            <Input prefix={<TeamOutlined />} placeholder="请输入角色名称" />
          </Form.Item>
          
          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea placeholder="请输入描述" rows={3} />
          </Form.Item>
          
          <Form.Item
            name="permissions"
            label="权限"
          >
            <Transfer
              dataSource={resources.map(r => ({
                key: r.id,
                title: r.name,
                description: r.description,
              }))}
              titles={['可用权限', '已分配权限']}
              targetKeys={currentRole?.permissions || []}
              render={(item) => item.title || ''}
              listStyle={{ width: 300, height: 400 }}
            />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
};

export default PermissionManager; 